// @ts-ignore
import { fabric as fbWithErasing } from "fabric-with-erasing";
import * as fbBasic from "fabric";

export const fabric: typeof fbBasic.fabric = fbWithErasing as any;
export const fabricWithErasing = fbWithErasing;

export const renderSvgIcon = (icon: HTMLImageElement) => {
  return function renderIcon(
    ctx: Record<string, any>,
    left: number,
    top: number,
    fabricObject: Record<string, any>,
  ) {
    const size = 28;
    ctx?.save?.();
    ctx?.translate?.(left, top);
    ctx?.rotate?.(fabric.util.degreesToRadians(fabricObject?.angle));
    ctx?.drawImage?.(icon, -size / 2, -size / 2, size, size);
    ctx?.restore?.();
  };
};

export const calcCanvasZoomLevel = (
  containerSize: { width: number; height: number },
  sketchSize: { width: number; height: number },
) => {
  if (
    sketchSize.width < containerSize.width &&
    sketchSize.height <= containerSize.height
  ) {
    return 1;
  }

  let level = 1;
  if (
    containerSize.width / containerSize.height <
    sketchSize.width / sketchSize.height
  ) {
    level = containerSize.width / sketchSize.width;
  } else {
    level = containerSize.height / sketchSize.height;
  }

  level = Number(level.toFixed(2));
  return level;
};

export const calcImgScaleFn = (params: {
  canvasWidth: number;
  canvasHeight: number;
  imgWidth: number;
  imgHeight: number;
}) => {
  if (!params || !Object.keys(params).length) return 1;

  const controlSize = 88;
  const canvasWidth = params?.canvasWidth || 0;
  const canvasHeight = params?.canvasHeight || 0;

  const imgWidth = params?.imgWidth || 0;
  const imgHeight = params?.imgHeight || 0;

  const scaleWidth = canvasWidth / imgWidth;
  const scaleHeight = (canvasHeight - controlSize) / imgHeight;

  return Math.min(scaleWidth, scaleHeight);
};

export const fixFloatingPoint = (value: number) => {
  const FLOATING_POINT_DIGIT = 2;
  return Number(value.toFixed(FLOATING_POINT_DIGIT));
};

export const _getPresetPropertiesForCropSize = (params: {
  presetRatio: number;
  sketchWidth: number;
  sketchHeight: number;
}) => {
  const originalWidth = params?.sketchWidth || 0;
  const originalHeight = params?.sketchHeight || 0;
  const presetRatio = params?.presetRatio || 1;

  const standardSize =
    originalWidth >= originalHeight ? originalWidth : originalHeight;
  const getScale = (value: number, orignalValue: number) =>
    value > orignalValue ? orignalValue / value : 1;

  let width = standardSize * presetRatio;
  let height = standardSize;

  const scaleWidth = getScale(width, originalWidth);
  [width, height] = [width, height].map((sizeValue) => sizeValue * scaleWidth);

  const scaleHeight = getScale(height, originalHeight);
  [width, height] = [width, height].map((sizeValue) =>
    fixFloatingPoint(sizeValue * scaleHeight),
  );

  return {
    presetRatio,
    top: (originalHeight - height) / 2,
    left: (originalWidth - width) / 2,
    width,
    height,
  };
};
